<?php
class ActListsController extends AppController {
    var $pageTitle = 'Aktifitas Harian';
    
    function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('orphan', 'get_courses');

        for ($i = 1; $i < 13; $i++) {
            $class_hours[$i] = '';
        }
        $class_hours[1]  .= '07.30';
        $class_hours[2]  .= '08.15';
        $class_hours[3]  .= '09.00';
        $class_hours[4]  .= '09.45';
        $class_hours[5]  .= '10.15';
        $class_hours[6]  .= '11.00';
        $class_hours[7]  .= '11.45';
        $class_hours[8]  .= '12.45';
        $class_hours[9]  .= '13.30';
        $class_hours[10] .= '14.30';
        $class_hours[11] .= '14.15';
        $class_hours[12] .= '15.00';
        
        $this->class_hours = $class_hours;
        $this->break_hours = array(4, 5, 7, 8);
    }
    
    function index() {
        $this->paginate['order'] = array(
            'ActList.activity_date' => 'DESC',
            'ActList.id' => 'DESC'
        );
        parent::index();
    }

    function approval_list() {
        $this->paginate['ActList']['order'] = array(
            'ActList.activity_date' => 'DESC',
            'ActList.id' => 'DESC'
        );
        $this->module_permission['show_all'] = true;
        // disable add and edit
        parent::index();
        $module_permission['operations'] = array(
            'add' => false, 'delete' => false, 'print' => false, 'csv' => false, 'pdf' => false,
            'edit' => true
        );
        $this->set('module_permission', $module_permission);
        $this->set('title_for_layout', 'Aktifitas Harian Yang Perlu Diverifikasi');
    }
    
    function verify() {
        $condition = array();

        $this->set('title_for_layout', 'Aktifitas Harian Yang Perlu Diverifikasi');
        $this->paginate['ActList']['order'] = array(
            'ActList.activity_date' => 'DESC',
            'ActList.id' => 'DESC',
        );

        // pass validation for a moment
        /*
        $_verified_positions = $this->ActList->CreatedBy->Position->children($this->Auth->user('position_id'), true);
        $__verified_positions = array();
        foreach ($_verified_positions as $_vp ) {
            $__verified_positions[ $_vp['Position']['id'] ] = $_vp['Position']['id'];
        }
        // filter created_by such that the users have positon_id verified by
        // user with $currentUnitCodeId
        $verified_users = $this->ActList->CreatedBy->find('list', array(
            'conditions' => array(
                'CreatedBy.position_id' => $__verified_positions,
            ),
            'fields' => array('id', 'id'), 'recursive' => -1
        ));

        // unit_code_id should be the same as study_program_id
        $currentUnitCodeId = $this->Auth->user('unit_code_id');

        $condition['ActList.created_by'] = $verified_users;
        if ( $currentUnitCodeId ) {
            $condition['ActList.currentUnitCodeId'] = $currentUnitCodeId;
        }*/

        // filter by field passed in tablegrid
        $str_fl = '';
        if ( isset($this->params['url']['search']) && $this->params['url']['search'] == 'Search' ) {
            App::import('Sanitize');
            $filtered_link   = array();
            $filtered_link[] = '?search=Search';
            
            foreach ( $this->params['url'] as $param => $value ) {
                if ( !empty($value) && $param != 'url' && $param != 'search' && $param != 'ref') {
                    $filtered_link[] = $param . "=" . $value;
                    $this->set($param . "Value", $value);
                    $like = str_replace('*', '%', Sanitize::paranoid($value, array('*', ' ', '-')));
                    $condition[$this->modelName.".$param LIKE"] = $like;
                }
            }
            
            if (!empty($filtered_link)) {
                $str_fl = implode("&", $filtered_link);
            }
        }
        
        // filter based on verificator unit_code_id/study_program_id
        // that he/she capable to verifiy of.
        $records = $this->paginate($condition);
        
        $this->set('str_fl', $str_fl);
        $this->set('records', $records);
        
        // disable add and edit
        $module_permission['operations'] = array(
            'add' => false, 'delete' => false, 'print' => false, 'csv' => false, 'pdf' => false,
            'edit' => true
        );
        $this->set('module_permission', $module_permission);
        
        $this->set('formgrid', Helper::url('delete_rows'));
    }

    function add() {
        // cek apakah hari ini sudah ada aktifitas dari user yang
        // bersangkutan

        // pass validation for temp as requested by Mr. Heru
        /*$exists = $this->ActList->find('count', array(
            'conditions' => array(
                'created_by' => $this->Auth->user('id'),
                'activity_date' => date('Y-m-d')
            ),
            'recursive' => -1
        ));*/
        $exists = false;

        if ( !$exists ) {
            $this->__setAdditionals();
            $this->__saving();
        } else {
            $this->Session->setFlash(
                'Sudah ada aktifitas yang diinput untuk hari ini, silahkan edit data tersebut jika ada perubahan.',
                'error'
            );
            $this->__redirect();
        }
    }

    function add_for_other() {
        $users = $this->ActList->CreatedBy->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('users', $users);

        // cek apakah hari ini sudah ada aktifitas dari user yang
        // bersangkutan
        $exists = $this->ActList->find('count', array(
            'conditions' => array(
                'created_by' => $this->Auth->user('id'),
                'activity_date' => date('Y-m-d')
            ),
            'recursive' => -1
        ));

        if ( !$exists ) {
            $this->__setAdditionals();
            $this->__saving();
        } else {
            $this->Session->setFlash(
                'Sudah ada aktifitas yang diinput untuk hari ini, silahkan edit data tersebut jika ada perubahan.',
                'error'
            );
            $this->__redirect();
        }
    }

    function edit($id = null) {
        $action = 'index';
        if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
            $action = 'verify';
        }
        
        if (!$id) {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
            $this->__redirect($action);
        }
        $this->set('id', $id);

        // first check wether user is a verificator or real user
        $this->ActList->Behaviors->attach('Containable');
        $user = $this->ActList->find('first', array(
            'conditions' => array('ActList.id' => $id), 'fields' => array('activity_date', 'verified_by', 'created_by', 'absent'),
            'contain' => array(
                'CreatedBy' => array(
                    'fields' => array('name', 'position_id')
                )
            )
        ));
        $verified_by = '';
        if ( isset($user['ActList']['created_by']) ) {
            $user_id = $user['ActList']['created_by'];
            $position_id = $user['CreatedBy']['position_id'];
            $name = $user['CreatedBy']['name'];
            
            $activity_date = $user['ActList']['activity_date'];
            $this->set('activity_date', $activity_date);
            
            $absent = $user['ActList']['absent'];
            $this->set('absent', $absent);
            
            $verified_by = $user['ActList']['verified_by'];
        } else {
            $this->Session->setFlash(__('Invalid parameter', true), 'error');
            $this->__redirect($action);
        }

        $this->__setAdditionals(1, $id, $user_id, $name, $position_id, $verified_by);
        $this->__saving(1, $id, $user_id, $position_id);
        
        if (empty($this->data)) {
            $this->data = $this->ActList->find('first', array(
                'conditions' => array('ActList.id' => $id)
            ));
            
            if (!$this->data) {
                $this->Session->setFlash(__('Invalid parameter', true), 'error');
                $this->__redirect($action);
            }
        } else {
            $this->data[$this->modelName]['id'] = $id;
        }

        $currentUnitCodeId = $this->Auth->user('unit_code_id');
        $this->set('currentUnitCodeId', $currentUnitCodeId);
    }
    
    function __saving($edit = false, $id = null, $user_id = null, $position_id = null) {
        if ( !empty($this->data) ) {
            // action to be redirected to
            // when operation failed or succeed
            $action = 'index';
            if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
                $action = 'verify';
            }
            $approver_position = $this->{$this->modelName}->getApprover();
            $approver = ($this->Auth->user('position_id') == $approver_position['id']) ? true : false;
            if ( $approver ) {
                $action = 'approval_list';
            }

            $messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                   ' ' . __('successfully added', true);
            $messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                 ' ' . __('cannot add this new record. Please fix the errors mentioned belows', true);
            if ( $edit ) {
                $messageFlashSuccess = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                       ' ' . __("successcully edited", true);
                $messageFlashError = (isset($this->niceName) ? $this->niceName : $this->modelName) .
                                     ' ' . __("cannot save this modification. Please fix the errors mentioned belows", true);
            }

            if ( !isset($this->data['ActList']['created']) || empty($this->data['ActList']['created']) ) {
                $created_date = date('Y-m-d');
            } else {
                $created_date = $this->data['ActList']['created']['year'] . '-' .
                                $this->data['ActList']['created']['month'] . '-' .
                                $this->data['ActList']['created']['day'];
            }

            if ( $edit ) {
                $this->ActList->id = $id;
                $not_user = ($this->Auth->user('position_id') != $position_id) ? true : false;

                if ($not_user && !$approver) {
                    $this->data['ActList']['verified'] = date('Y-m-d H:i:s');
                    $this->data['ActList']['verified_by'] = $this->Auth->user('position_id');
                }
                if ($approver) {
                    $this->data['ActList']['approved'] = date('Y-m-d H:i:s');
                    $this->data['ActList']['approved_by'] = $this->Auth->user('position_id');
                }
            } else {
                $verificator = $this->ActList->getVerificator( $this->Auth->user('id') );
                
                $this->data['ActList']['activity_date'] = $created_date;
                $this->data['ActList']['created'] = $created_date . ' 00:00:00';
                $this->data['ActList']['modified'] = $created_date . ' 00:00:00';
                $this->data['ActList']['verified_by'] = $verificator['id'];
                $this->data['ActList']['approved_by'] = $approver_position['id'];
                $this->ActList->create();
            }
            $lists = $this->data;
            
            if ($this->ActList->save($this->data)) {
                // on editing we need to delete all
                // act_list_activity and descriptions
                // whose act_list_id is $id
                if ( $edit && $id ) {
                    // get created_by, since
                    // we are delete all children
                    $created_by = $this->ActList->find('first', array(
                        'conditions' => array(
                            'ActList.id' => $id
                        ),
                        'fields' => array('ActList.created_by'),
                        'recursive' => -1
                    ));
                    $created_by = $created_by['ActList']['created_by'];
                    
                    $this->ActList->ActListActivity->deleteAll(
                        array('ActListActivity.act_list_id' => $id),
                        true,
                        true
                    );
                }
				
                // set list_id, created_by and modified_by
                foreach ( $this->data['ActList']['ActListActivity'] as $key => $bd ) {
                    $this->data['ActList']['ActListActivity'][$key]['act_list_id'] = $this->ActList->id;
                    
                    // save act_list_activity one by one
                    $this->ActList->ActListActivity->create();
                    if ( $this->ActList->ActListActivity->save($this->data['ActList']['ActListActivity'][$key]) ) {
                        // set act_list_activity_id, created_by or modified_by
                        // on ActListActivityDescription
                        foreach ( $this->data['ActList']['ActListActivity']
                            [$key]['ActListActivityDescription'] as $key2 => $bdd ) {
                                
                            $this->data['ActList']['ActListActivity']
                                [$key]['ActListActivityDescription']
                                [$key2]['act_list_activity_id'] = $this->ActList->ActListActivity->id;
                        }
                        
                        // save all description per each act_list_activity_id
                        $this->ActList->ActListActivity->ActListActivityDescription->create();
                        if  ( $this->ActList->ActListActivity->ActListActivityDescription->saveAll(
                              $this->data['ActList']['ActListActivity'][$key]['ActListActivityDescription']) )
                        {
                            // save all absent students on callback
                            
                        } else { // failed savingAll description
                            $this->set('lists', $lists['ActList']);
                            $this->Session->setFlash($messageFlashError, 'error');
                        }
                    // eof saving detail
                    } else { // failed saving list_activities
                        $this->set('lists', $lists['ActList']);
                        $this->Session->setFlash($messageFlashError, 'error');
                    }
                } // eof set list_id
                $this->Session->setFlash( $messageFlashSuccess, 'success');
                $this->__redirect($action);
            } else { // failed saving lists
                $this->set('lists', $lists['ActList']);
                $this->Session->setFlash($messageFlashError, 'error');
            }
        }
    }
    
    function __setAdditionals($edit = false, $id = null, $user_id = null, $name = null, $position_id = null, $verified_by = '') {
        // action to be redirected to
        // when operation failed or succeed
        $action = 'index';
        if ( isset($this->params['url']['verify']) && $this->params['url']['verify'] ) {
            $action = 'verify';
            $this->set('action_suffix', $action);
        }
        
        // student_classes
        $_student_classes = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->find('all', array(
            'recursive' => -1, 'order' => 'name'
        ));
        $student_classes = array();
        foreach ($_student_classes as $_sc) {
            $student_classes[$_sc['StudentClass']['id']] = $_sc['StudentClass']['name'] . ' (Angkatan ' . $_sc['StudentClass']['year_started'] . ')';
        }
        $this->set('student_classes', $student_classes);
        
        $this->set('class_hours', $this->class_hours);
        
        // courses
        $courses = $this->ActList->ActListActivity->ActListActivityDescription->Course->find('list');
        $this->set('courses', $courses);
        
        // check if user is a real user or verificator or approver
        // just on edit
        $not_user = false;
        $approver = false;
        $action_back = 'index';
        $approver_position = array();
        if ( $edit && $id ) {
            $not_user = ($this->Auth->user('position_id') != $position_id) ? true : false;
            $approver_position = $this->ActList->getApprover();
            $approver = ($this->Auth->user('position_id') == $approver_position['id']) ? true : false;
            if ( $approver ) {
                $not_user = true;
                $action_back = 'approval_list';
            }
        }
        $this->set(compact('not_user', 'approver', 'approver_position'));
        
        $position_id_condition = $this->Auth->user('position_id');
        $user_id_condition = $this->Auth->user('id');
        $creator_name = $this->Auth->user('name');
        // assumed as verificator or admin
        if ( $edit && $not_user ) {
            $position_id_condition = $position_id;
            $user_id_condition = $user_id;
            $creator_name = $name;
            $action_back = 'verify';
        }
        $this->set('action_back', $action_back);
        
        // absent options
        $this->set('absent_options', $this->ActList->generateAbsentOptions());
        // creator name
        $this->set('creator_name', $creator_name);
        
        // my position
        $my_position = $this->ActList->CreatedBy->Position->find('first', array(
            'conditions' => array('id' => $position_id_condition),
            'recursive' => -1, 'fields' => array('name')
        ));
        $this->set('my_position', $my_position['Position']['name']);
        
        // verificator position
        if ( !empty($verified_by) ) {
            $verificator_position = $this->ActList->CreatedBy->Position->find('first', array(
                'fields' => array('id', 'name'), 'recursive' => -1, 'conditions' => array('id' => $verified_by)
            ));
            $verificator = $verificator_position['Position'];
            $this->set('verificator_position', $verificator_position['Position']['name']);
            $this->set('verificator_position_id', $verified_by);
        } else {
            $verificator = $this->ActList->getVerificator( $user_id_condition );
            $this->set('verificator_position', $verificator['name']);
            $this->set('verificator_position_id', $verificator['id']);
        }
        
        // if not an creator nor an admin nor a verificator
        if ( $edit && !$approver && $not_user && $this->Auth->user('group_id') != 1 &&
             $verificator['id'] != $this->Auth->user('position_id'))
        {
            $this->Session->setFlash(__('Anda tidak punya akses untuk melihat', true), 'error');
            $this->__redirect($action);
        }
        
        // kegiatan
        $activities = $this->ActList->ActListActivity->Activity->find('list', array(
            'conditions' => array(
                'Activity.position_id' => $position_id_condition
            )
        ));
        // special activities
        $special_activities = $this->ActList->ActListActivity->Activity->find('list', array(
            'conditions' => array(
                'Activity.position_id' => $position_id_condition,
                'Activity.special' => 1
            ),
            'fields' => array('id', 'id')
        ));
        $this->set('activities', $activities);
        $this->set('special_activities', $special_activities);
        
        if ( $edit ) {
            // get act_lists
            $this->ActList->Behaviors->attach('Containable');
            $lists = $this->ActList->find('first', array(
                'conditions' => array(
                    'ActList.id' => $id
                ),
                'contain' => array(
                    'ActListActivity' => array(
                        'ActListActivityDescription' => array(
                            'order' => 'ActListActivityDescription.id ASC',
                            'StudentClass' => array(
                                'Student'
                            ),
                            'ActListActivityDescriptionStudent'
                        ),
                        'order' => 'ActListActivity.id ASC'
                    )
                ),
                'order' => 'ActList.id ASC'
            ));
            $this->set('lists', $lists);
        }
        
        // set ajax URL
        $prefix = parent::__pathToController() . '/getOptions';
        $getStudents = $this->webroot . 'student_classes/getStudents/';
        $getCourses = $this->webroot . 'courses/getCourses/';
        $this->set('prefixURL', $prefix);
        $this->set('getStudents', $getStudents);
        $this->set('getCourses', $getCourses);

        $this->set('getProfileURL', parent::__pathToController() . '/get_profile');
    }
    
    function report_per_day($tpl = '') {
        $show_form = true;
        $tpl_view = 'report_per_day';
        
        $users = $this->ActList->CreatedBy->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('users', $users);
        
        if ( isset($this->data['ActList']['date']) && !empty($this->data['ActList']['date']) ) {
            $show_form = false;
            //Configure::write('debug', 0);
            $this->layout = 'printhtml';

            // date in a day
            if ( isset($this->data['ActList']['date']['day']) ) {
                $date = $this->data['ActList']['date']['year'] . '-' . $this->data['ActList']['date']['month'] . '-' .
                        $this->data['ActList']['date']['day'];
                $conditions['ActList.activity_date'] = $date;
            } else {
                $min_date = $this->data['ActList']['date']['year'] . '-' .
                            $this->data['ActList']['date']['month'] . '-01';
                $max_date = $this->data['ActList']['date']['year'] . '-' .
                            $this->data['ActList']['date']['month'] . '-31';
                $conditions = array(
                    'ActList.activity_date >=' => $min_date,
                    'ActList.activity_date <=' => $max_date
                );
                $date = $this->getMonthName($this->data['ActList']['date']['month']) . ' ' .
                        $this->data['ActList']['date']['year'];
            }
            // readable date to be outputted in view
            $this->set('date', $date);
            
            // check if user is passed or all is selected
            if ( isset($this->data['ActList']['user']) && !empty($this->data['ActList']['user']) ) {
                $conditions['ActList.created_by'] = $this->data['ActList']['user'];
                $this->ActList->CreatedBy->Behaviors->attach('Containable');
                $user = $this->ActList->CreatedBy->find('first', array(
                    'fields' => array('CreatedBy.name', 'CreatedBy.nip'),
                    'conditions' => array(
                        'CreatedBy.id' => $this->data['ActList']['user']
                    ),
                    'contain' => array(
                        'UnitCode' => array(
                            'fields' => array('name')
                        ),
                        'Position' => array(
                            'fields' => array('name')
                        )
                    )
                ));
                if ( !empty($user) ) {
                    $this->set('user', $user);
                }
            }
            
            $activityIdOfTeaching = $this->ActList->ActListActivity->Activity->find('list', array(
                'conditions' => array(
                    'Activity.special' => 1
                ),
                'recursive' => -1, 'fields' => array('id', 'id')
            ));
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array(
                                'description', 'assignment_no', 'verified', 'start_class', 'end_class',
                                'verified', 'approved'
                            ),
                            'Course', 'StudentClass'
                        )
                    )
                ),
                'order' => 'ActList.activity_date ASC, ActList.id ASC'
            ));
            
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');

            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = isset($record['CreatedBy']['UnitCode']['name']) ?
                                                                $record['CreatedBy']['UnitCode']['name'] : '';
                $records[$key]['CreatedBy']['position_name'] = isset($record['CreatedBy']['Position']['name']) ?
                                                               $record['CreatedBy']['Position']['name'] : '';
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 )  // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // absent nice name
                $records[$key]['ActList']['absent'] = $absent_options[$records[$key]['ActList']['absent']];
                
                if ( !empty($record['ActListActivity']) ) {
                    // all activities
                    $records[$key]['ActList']['activity'] = '<ol>';
                    // teaching activity, which is special field is True
                    $records[$key]['ActList']['teaching'] = '<ul>';
                    $records[$key]['ActList']['teaching_classes'] = '<ul>';
                    $records[$key]['ActList']['teaching_time'] = '<ul>';
                    $records[$key]['ActList']['teaching_time_qty'] = '<ul>';
                    $records[$key]['ActList']['teaching_semester'] = '<ul>';
                    $records[$key]['ActList']['teaching_verified'] = '<ul>';
                    $records[$key]['ActList']['teaching_approved'] = '<ul>';
                    $records[$key]['ActList']['teaching_materials'] = '<ul>';
                    $records[$key]['ActList']['teaching_students_qty'] = '<ul>';
                    
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        
                        $records[$key]['ActList']['activity'] .= '<li>' . $activity['Activity']['name'];
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( in_array($activity['activity_id'], $activityIdOfTeaching) &&
                                     !empty($desc['Course']) )
                                {
                                    $records[$key]['ActList']['teaching'] .= '<li>' . $desc['Course']['name'] . ' (' . $desc['Course']['sks'] . ' SKS)</li>';
                                    $records[$key]['ActList']['teaching_classes'] .= '<li>' . $desc['StudentClass']['name'] . ' (Angkatan ' . $desc['StudentClass']['year_started'] . ')</li>';
                                    $records[$key]['ActList']['teaching_time'] .= '<li>' .
                                                             ((!empty($desc['start_class']) &&
                                                               !empty($desc['end_class'])) ?
                                                               ($this->class_hours[$desc['start_class']] . ' - ' .
                                                                $this->class_hours[$desc['end_class']]) : '');
                                    
                                    $records[$key]['ActList']['teaching_time_qty'] .= '<li>' .
                                        $this->__getTimeQty($desc['start_class'], $desc['end_class']);
                                    $records[$key]['ActList']['teaching_time'] .= '</li>';
                                    $records[$key]['ActList']['teaching_semester'] .= '<li>' .
                                                                                      $desc['Course']['semester'] .
                                                                                      '</li>';
                                    $records[$key]['ActList']['teaching_verified'] .= '<li>';
                                    if ( $desc['verified'] ) {
                                        $records[$key]['ActList']['teaching_verified'] .= '&radic;';
                                    }
                                    $records[$key]['ActList']['teaching_verified'] .= '</li>';
                                    
                                    $records[$key]['ActList']['teaching_approved'] .= '<li>';
                                    if ( $desc['approved'] ) {
                                        $records[$key]['ActList']['teaching_approved'] .= '&radic;';
                                    }
                                    $records[$key]['ActList']['teaching_approved'] .= '</li>';
                                    
                                    // jumlah mahasiswa yang hadir
                                    $records[$key]['ActList']['teaching_students_qty'] .= '<li>';
                                    if ( !isset($tsoac[$desc['student_class_id']]) ) {
                                        $records[$key]['ActList']['teaching_students_qty'] .= 0;
                                    } else {
                                        $records[$key]['ActList']['teaching_students_qty'] .=
                                            ($tsoac[$desc['student_class_id']] -
                                             count($desc['ActListActivityDescriptionStudent']));
                                    }
                                    $records[$key]['ActList']['teaching_students_qty'] .= '</li>';
                                    
                                    // materi
                                    $records[$key]['ActList']['teaching_materials'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                                
                                if ( !empty($desc['description']) ) {
                                    if ( !empty($desc['assignment_no']) ) {
                                        $desc['description'] .= ' &mdash; No surat tugas ' . $desc['assignment_no'];
                                    }
                                    if ( $desc['verified'] ) {
                                        $desc['description'] .= ' &radic;';
                                        
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                    $records[$key]['ActList']['activity'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                            }
                            $records[$key]['ActList']['activity'] .= '</ol>';
                        }
                        $records[$key]['ActList']['activity'] .= '</li>';
                    }
                    $records[$key]['ActList']['activity'] .= '</ol>';
                    $records[$key]['ActList']['teaching'] .= '</ul>';
                    $records[$key]['ActList']['teaching_classes'] .= '</ul>';
                    $records[$key]['ActList']['teaching_time'] .= '</ul>';
                    $records[$key]['ActList']['teaching_semester'] .= '</ul>';
                    $records[$key]['ActList']['teaching_verified'] .= '</ul>';
                    $records[$key]['ActList']['teaching_approved'] .= '</ul>';
                    $records[$key]['ActList']['teaching_materials'] .= '</ul>';
                    $records[$key]['ActList']['teaching_students_qty'] .= '</ul>';
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
            }
            
            $this->set('records', $records);
        }
        switch ($tpl) {
            case 'teaching':
                $tpl_view = 'report_per_day_teaching';
                break;
            case 'teaching_monthly':
                $tpl_view = 'report_per_day_teaching_monthly';
                break;
        }
        
        $this->set('show_form', $show_form);
        $this->set('tpl', $tpl);
        $this->render($tpl_view);
    }
    
    /* Report for lecture to get his/her own attendances. Visible to
     * lecture.
     */
    function report_for_me() {
        $show_form = true;
        
        if ( isset($this->data['ActList']['date']) && !empty($this->data['ActList']['date']) ) {
            $show_form = false;
            $this->layout = 'printhtml';

            $min_date = $this->data['ActList']['date']['year'] . '-' .
                        $this->data['ActList']['date']['month'] . '-01';
            $max_date = $this->data['ActList']['date']['year'] . '-' .
                        $this->data['ActList']['date']['month'] . '-31';
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            $conditions['ActList.created_by'] = $this->Auth->user('id');
            
            $date = $this->getMonthName($this->data['ActList']['date']['month']) . ' ' .
                    $this->data['ActList']['date']['year'];
            // readable date to be outputted in view
            $this->set('date', $date);
            
            $activityIdOfTeaching = $this->ActList->ActListActivity->Activity->find('list', array(
                'conditions' => array(
                    'Activity.special' => 1
                ),
                'recursive' => -1, 'fields' => array('id', 'id')
            ));
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array(
                                'description', 'assignment_no', 'verified', 'student_class_id',
                                'start_class', 'end_class', 'verified', 'approved'
                            ),
                            'Course', 'StudentClass', 'ActListActivityDescriptionStudent'
                        )
                    )
                ),
                'order' => 'ActList.activity_date ASC, ActList.id ASC'
            ));
            
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // get total students of available classes
            $_tsoac = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->Student->find(
                'all', array(
                    'fields' => array('Student.student_class_id', 'COUNT(Student.id) as total'),
                    'recursive' => -1,
                    'group' => 'student_class_id'
                )
            );
            $tsoac = array();
            foreach ($_tsoac as $__tsoac) {
                $tsoac[$__tsoac['Student']['student_class_id']] = $__tsoac[0]['total'];
            }

            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = isset($record['CreatedBy']['UnitCode']['name']) ?
                                                                $record['CreatedBy']['UnitCode']['name'] : '';
                $records[$key]['CreatedBy']['position_name'] = isset($record['CreatedBy']['Position']['name']) ?
                                                               $record['CreatedBy']['Position']['name'] : '';
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 )  // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // absent nice name
                $records[$key]['ActList']['absent'] = $absent_options[$records[$key]['ActList']['absent']];
                
                if ( !empty($record['ActListActivity']) ) {
                    // all activities
                    $records[$key]['ActList']['activity'] = '<ol>';
                    // teaching activity, which is special field is True
                    $records[$key]['ActList']['teaching'] = '<ul>';
                    $records[$key]['ActList']['teaching_classes'] = '<ul>';
                    $records[$key]['ActList']['teaching_time'] = '<ul>';
                    $records[$key]['ActList']['teaching_time_qty'] = '<ul>';
                    $records[$key]['ActList']['teaching_semester'] = '<ul>';
                    $records[$key]['ActList']['teaching_verified'] = '<ul>';
                    $records[$key]['ActList']['teaching_approved'] = '<ul>';
                    $records[$key]['ActList']['teaching_materials'] = '<ul>';
                    $records[$key]['ActList']['teaching_students_qty'] = '<ul>';
                    
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        
                        $records[$key]['ActList']['activity'] .= '<li>' . $activity['Activity']['name'];
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( in_array($activity['activity_id'], $activityIdOfTeaching) &&
                                     !empty($desc['Course']) )
                                {
                                    $records[$key]['ActList']['teaching'] .= '<li>' . $desc['Course']['name'] . ' (' . $desc['Course']['sks'] . ' SKS)</li>';
                                    $records[$key]['ActList']['teaching_classes'] .= '<li>' . $desc['StudentClass']['name'] . ' (Angkatan ' . $desc['StudentClass']['year_started'] . ')</li>';
                                    $records[$key]['ActList']['teaching_time'] .= '<li>' .
                                                             ((!empty($desc['start_class']) &&
                                                               !empty($desc['end_class'])) ?
                                                               ($this->class_hours[$desc['start_class']] . ' - ' .
                                                                $this->class_hours[$desc['end_class']]) : '');
                                    
                                    $records[$key]['ActList']['teaching_time_qty'] .= '<li>' .
                                        $this->__getTimeQty($desc['start_class'], $desc['end_class']);
                                    $records[$key]['ActList']['teaching_time'] .= '</li>';
                                    $records[$key]['ActList']['teaching_semester'] .= '<li>' .
                                                                                      $desc['Course']['semester'] .
                                                                                      '</li>';
                                    $records[$key]['ActList']['teaching_verified'] .= '<li>';
                                    if ( $desc['verified'] ) {
                                        $records[$key]['ActList']['teaching_verified'] .= '&radic;';
                                    }
                                    $records[$key]['ActList']['teaching_verified'] .= '</li>';
                                    
                                    $records[$key]['ActList']['teaching_approved'] .= '<li>';
                                    if ( $desc['approved'] ) {
                                        $records[$key]['ActList']['teaching_approved'] .= '&radic;';
                                    }
                                    $records[$key]['ActList']['teaching_approved'] .= '</li>';
                                    
                                    // jumlah mahasiswa yang hadir
                                    $records[$key]['ActList']['teaching_students_qty'] .= '<li>';
                                    if ( !isset($tsoac[$desc['student_class_id']]) ) {
                                        $records[$key]['ActList']['teaching_students_qty'] .= 0;
                                    } else {
                                        $records[$key]['ActList']['teaching_students_qty'] .=
                                            ($tsoac[$desc['student_class_id']] -
                                             count($desc['ActListActivityDescriptionStudent']));
                                    }
                                    $records[$key]['ActList']['teaching_students_qty'] .= '</li>';
                                    
                                    // materi
                                    $records[$key]['ActList']['teaching_materials'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                                
                                if ( !empty($desc['description']) ) {
                                    if ( !empty($desc['assignment_no']) ) {
                                        $desc['description'] .= ' &mdash; No surat tugas ' . $desc['assignment_no'];
                                    }
                                    if ( $desc['verified'] ) {
                                        $desc['description'] .= ' &radic;';
                                        
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                    $records[$key]['ActList']['activity'] .=  '<li>' . $desc['description'] . '</li>';
                                }
                            }
                            $records[$key]['ActList']['activity'] .= '</ol>';
                        }
                        $records[$key]['ActList']['activity'] .= '</li>';
                    }
                    $records[$key]['ActList']['activity'] .= '</ol>';
                    $records[$key]['ActList']['teaching'] .= '</ul>';
                    $records[$key]['ActList']['teaching_classes'] .= '</ul>';
                    $records[$key]['ActList']['teaching_time'] .= '</ul>';
                    $records[$key]['ActList']['teaching_semester'] .= '</ul>';
                    $records[$key]['ActList']['teaching_verified'] .= '</ul>';
                    $records[$key]['ActList']['teaching_approved'] .= '</ul>';
                    $records[$key]['ActList']['teaching_materials'] .= '<ul>';
                    $records[$key]['ActList']['teaching_students_qty'] .= '<ul>';
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
            }
            
            $this->set('records', $records);
        }
        
        $this->set('show_form', $show_form);
    }
    
    function report_student_attendance($tpl = '') {
        $show_form = true;
        $tpl_view = 'report_student_attendance';
        
        $student_classes = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->find(
            'all', array(
                'fields' => array('id', 'name', 'year_started'),
                'order' => 'name ASC, year_started ASC',
                'recursive' => -1
            )
        );
        $student_classes_list = array();
        foreach ($student_classes as $sc) {
            $student_classes_list[$sc['StudentClass']['id']] = $sc['StudentClass']['name'] . ' (Angkatan ' .
                                                               $sc['StudentClass']['year_started'] . ')';
        }
        $this->set('student_classes', $student_classes_list);
        
        if ( isset($this->data['ActList']['date']) && !empty($this->data['ActList']['date']) ) {
            $show_form = false;
            $this->layout = 'printhtml';
            $month = $this->data['ActList']['date']['month'];
            $year = $this->data['ActList']['date']['year'];
            $course_id = isset($this->data['ActList']['course']) ? $this->data['ActList']['course'] : '';
            $course = '';
            if ( $course_id ) {
                $_course = $this->ActList->ActListActivity->ActListActivityDescription->Course->find('first', array(
                    'conditions' => array(
                        'Course.id' => $course_id
                    )
                ));
                $course = $_course['Course']['name'];
            }

            $min_date = $year . '-' . $month . '-01';
            $max_date = $year . '-' . $month . '-31';
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            $date = $this->getMonthName($this->data['ActList']['date']['month']) . ' ' .
                    $this->data['ActList']['date']['year'];
            
            $conditions_class = array();
            // check if user is class is passed or all is selected
            if ( isset($this->data['ActList']['class']) && !empty($this->data['ActList']['class']) ) {
                $conditions_class['id'] = $this->data['ActList']['class'];
                $this->set('class', $student_classes_list[$this->data['ActList']['class']]);
            }
            
            // get all student from current class
            $students = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->Student->find(
                'all', array(
                    'conditions' => array(
                        'Student.student_class_id' => $this->data['ActList']['class']
                    ),
                    'order' => 'Student.name ASC'
                )
            );
            // iterate students and restructurized the array to handle weeks and days
            $class = '';
            $year_started = '';
            foreach ($students as $k => $s) {
                $students[$k]['Student']['attendance'] = array(
                    array(0,0,0,0,0,0,0),array(0,0,0,0,0,0,0),array(0,0,0,0,0,0,0),
                    array(0,0,0,0,0,0,0),array(0,0,0,0,0,0,0)
                );
                $class = $s['StudentClass']['name'];
                $year_started = $s['StudentClass']['year_started'];
            }
            
            $activityIdOfTeaching = $this->ActList->ActListActivity->Activity->find('list', array(
                'conditions' => array(
                    'Activity.special' => 1
                ),
                'recursive' => -1, 'fields' => array('id', 'id')
            ));
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip')
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'ActListActivityDescriptionStudent',
                            'Course',
                            'StudentClass' => array(
                                'conditions' => $conditions_class
                            ),
                            'fields' => array(
                                'description', 'assignment_no', 'verified', 'start_class', 'end_class',
                                'verified', 'approved', 'course_id'
                            ),
                            'order' => 'start_class ASC',
                        )
                    )
                ),
                'order' => 'ActList.activity_date ASC, ActList.id ASC'
            ));

            $semester = '';
            $attendance = array();
            foreach ($records as $key => $record) {
                if ( !empty($record['ActListActivity']) ) {
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( in_array($activity['activity_id'], $activityIdOfTeaching) &&
                                     !empty($desc['Course']) &&
                                     $this->data['ActList']['class'] == $desc['student_class_id'] &&
                                     $desc['approved'] && $desc['verified'] )
                                {
                                    // check if course is passed and filter it
                                    if ( $course_id && $desc['course_id'] != $course_id ) {
                                        continue;
                                    }
                                    if ( !isset($attendance[$record['ActList']['activity_date']]) ) {
                                        $attendance[$record['ActList']['activity_date']] = array(
                                            'teaching_time_qty' => 0,
                                            'student_absent' => array()
                                        );
                                    }
                                    $time_qty = $this->__getTimeQty($desc['start_class'], $desc['end_class']);
                                    $duration = $time_qty ? $time_qty : 0;
                                    $attendance[$record['ActList']['activity_date']]['teaching_time_qty'] += $duration;
                                    $semester = $desc['Course']['semester'];
                                    
                                    // mahasiswa yang tidak hadir
                                    foreach ($desc['ActListActivityDescriptionStudent'] as $s) {
                                        if ( !isset( $attendance[$record['ActList']['activity_date']]
                                                                ['student_absent'][$s['student_id']]) )
                                        {
                                            $attendance[$record['ActList']['activity_date']]
                                                       ['student_absent'][$s['student_id']] = $duration;
                                        } else {
                                            $attendance[$record['ActList']['activity_date']]
                                                       ['student_absent'][$s['student_id']] += $duration;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            $sp = array();
            $sp[1] = $this->Session->read('Site.sp1') ? $this->Session->read('Site.sp1') : 10;
            $sp[2] = $this->Session->read('Site.sp2') ? $this->Session->read('Site.sp2') : 20;
            $sp[3] = $this->Session->read('Site.sp3') ? $this->Session->read('Site.sp3') : 25;
            $sp[4] = $this->Session->read('Site.sp4') ? $this->Session->read('Site.sp4') : 26;
            $total_in     = array();
            $total_absent = array();
            foreach ($students as $k => $s) {
                $total_in[$s['Student']['id']] = 0;
                $total_absent[$s['Student']['id']] = 0;
                $current_week = 0;
                for ($i = 0; $i < 31; $i++) {
                    $d = str_pad($i+1, 2, '0', STR_PAD_LEFT);
                    $current_date = $year . '-' . $month . '-' . $d;
                    $_w = getdate(strtotime($current_date));
                    $w = $_w['wday'];
                    
                    // who's absent
                    if ( isset($attendance[$current_date]) ) {
                         if ( array_key_exists($s['Student']['id'], $attendance[$current_date]['student_absent']) &&
                              $w > 0 && $w < 6)
                        {
                            $students[$k]['Student']['attendance'][$current_week][$w] = 
                                $attendance[$current_date]['student_absent'][$s['Student']['id']];
                            $total_absent[$s['Student']['id']] += $attendance[$current_date]['student_absent']
                                                                            [$s['Student']['id']];
                            $total_in[$s['Student']['id']] += ($attendance[$current_date]['teaching_time_qty'] -
                                                               $students[$k]['Student']['attendance'][$current_week][$w]);
                        } else {
                            $students[$k]['Student']['attendance'][$current_week][$w] = '&radic;';
                            $total_in[$s['Student']['id']] += $attendance[$current_date]['teaching_time_qty'];
                        }
                        
                        
                    }
                    
                    if ( $w == 6 ) {
                        $current_week++;
                    }
                }

                // determine sp
                $students[$k]['Student']['sp'] = '';
                if ( $total_absent[$s['Student']['id']] >= $sp[1] && $total_absent[$s['Student']['id']] < $sp[2] ) {
                    $students[$k]['Student']['sp'] = 1;
                } else if ( $total_absent[$s['Student']['id']] >= $sp[2] && $total_absent[$s['Student']['id']] < $sp[3] ) {
                    $students[$k]['Student']['sp'] = 2;
                } else if ( $total_absent[$s['Student']['id']] >= $sp[3] && $total_absent[$s['Student']['id']] < $sp[4] ) {
                    $students[$k]['Student']['sp'] = 3;
                } else if ( $total_absent[$s['Student']['id']] >= $sp[4] ) {
                    $students[$k]['Student']['sp'] = 4;
                }
            }
            
            $week_name = array(0 => 'S', 1 => 'S', 2 => 'R', 3 => 'K', 4 => 'J');
            $this->set(compact(
                'week_name', 'date', 'class', 'semester', 'year_started', 'students', 'total_absent', 'total_in',
                'sp', 'course'
            ));
            
        }
        switch ($tpl) {
            case 'per_course':
                $tpl_view = 'report_student_attendance_per_course';
                break;
        }
        
        
        $this->set('show_form', $show_form);
        $this->set('get_courses_url', $this->__pathToController() . '/get_courses/');
        $this->set('tpl', $tpl);
        $this->render($tpl_view);
    }
    
    function report_per_month($tpl = '') {
        $show_form = true;
        $tpl_view = 'report_per_month';
        
        $users = $this->ActList->CreatedBy->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('users', $users);
        
        if ( !empty($this->data['month']['month']) && !empty($this->data['year']['year']) ) {
            $show_form = false;
            //Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $min_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-01';
            $max_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-31';
            $date = $this->getMonthName($this->data['month']['month']) . ' ' . $this->data['year']['year'];
            $this->set('date', $date);
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            if ( isset($this->data['ActList']['user']) && !empty($this->data['ActList']['user']) ) {
                $conditions['ActList.created_by'] = $this->data['ActList']['user'];
                $this->ActList->CreatedBy->Behaviors->attach('Containable');
                $user = $this->ActList->CreatedBy->find('first', array(
                    'fields' => array('CreatedBy.name', 'CreatedBy.nip'),
                    'conditions' => array(
                        'CreatedBy.id' => $this->data['ActList']['user']
                    ),
                    'contain' => array(
                        'UnitCode' => array(
                            'fields' => array('name')
                        ),
                        'Position' => array(
                            'fields' => array('name')
                        )
                    )
                ));
                if ( !empty($user) ) {
                    $this->set('user', $user);
                }
            }
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'StudentClass', 'Course',
                            'ActListActivityDescriptionStudent' => array(
                                'Student'
                            )
                        )
                    )
                )
            ));
            
            // options var
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $this->set('absent_options', $absent_options);
            
            // insentive var from session
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // total insentive and performance
            $total_insentive = 0;
            $total_perfomance = 0;
            
            // total per absent type
            $total_hadir = $absent_options;
            foreach ( $total_hadir as $thk => $thv ) {
                $total_hadir[ $thk ] = 0;
            }
            
            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = isset($record['CreatedBy']['UnitCode']['name']) ?
                                                                $record['CreatedBy']['UnitCode']['name'] : '';
                $records[$key]['CreatedBy']['position_name'] = isset($record['CreatedBy']['Position']['name']) ?
                                                               $record['CreatedBy']['Position']['name'] : '';
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 ) // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // total absent per type
                // NOTE : need to be above the overriden of absent nice name below
                $total_hadir[ $records[$key]['ActList']['absent'] ]++;
                
                // absent nice name
                $records[$key]['ActList']['absent'] = $absent_options[$records[$key]['ActList']['absent']];
                
                if ( !empty($record['ActListActivity']) ) {
                    $records[$key]['ActList']['activity'] = '<ol>';
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        $records[$key]['ActList']['activity'] .= '<li>' . $activity['Activity']['name'];
                        
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                $detail  = $desc['StudentClass']['name'] . ' angkatan ' .
                                           $desc['StudentClass']['year_started'] . '. ';
                                $detail .= 'Mata kuliah ' . $desc['Course']['name'] . ', semester ' .
                                           $desc['Course']['semester'] . ' (' . $desc['Course']['sks'] . ' sks).';
                                if ( !empty($desc['assignment_no']) ) {
                                    $desc['description'] .= ' &mdash; No surat tugas ' . $desc['assignment_no'];
                                }
                                if ( $desc['verified'] ) {
                                    $detail .= ' &radic;';
                                    
                                    if ( $records[$key]['ActList']['performance'] < 100 ) {
                                        $records[$key]['ActList']['performance'] += 20;
                                    }
                                }
                                $records[$key]['ActList']['activity'] .=  '<li>' . $detail . '</li>';
                            }
                            $records[$key]['ActList']['activity'] .= '</ol>';
                        }
                        $records[$key]['ActList']['activity'] .= '</li>';
                    }
                    $records[$key]['ActList']['activity'] .= '</ol>';
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
                
                // accumulate total for insentive and performance
                $total_insentive += $records[$key]['ActList']['insentive'];
                $total_perfomance += $records[$key]['ActList']['performance'];
            }
            
            switch ($tpl) {
                case 'teaching':
                    $tpl_view = 'report_per_month_teaching';
                    break;
            }
            
            $this->set('records', $records);
            $this->set('total_insentive', $total_insentive);
            $this->set('total_perfomance', $total_perfomance / count($records));
            $this->set('total_hadir', $total_hadir);
        }
        
        $this->set('show_form', $show_form);
        $this->set('tpl', $tpl);
        $this->render($tpl_view);
    }
    
    function report_per_month_summary() {
        $show_form = true;
        $unit_codes = $this->ActList->CreatedBy->UnitCode->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('unit_codes', $unit_codes);
        
        if ( !empty($this->data['month']['month']) && !empty($this->data['year']['year']) ) {
            $show_form = false;
            Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $min_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-01';
            $max_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-31';
            $date = $this->getMonthName($this->data['month']['month']) . ' ' . $this->data['year']['year'];
            $this->set('date', $date);
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            
            // get unit_code name from selected unit_code_id
            $unit_code = $this->ActList->CreatedBy->UnitCode->find('first', array(
                'fields' => array('UnitCode.name'),
                'conditions' => array('UnitCode.id' => $this->data['ActList']['unit_code']),
                'recursive' => -1
            ));
            if ( !empty($unit_code) ) {
                $this->set('unit_code', $unit_code['UnitCode']['name']);
            }
            
            // get users from selected unit_code
            $users = array();
            $_users = $this->ActList->CreatedBy->find('all', array(
                'fields' => array('CreatedBy.id'),
                'conditions' => array(
                    'CreatedBy.unit_code_id' => $this->data['ActList']['unit_code']
                ),
                'recursive' => -1
            ));
            foreach ( $_users as $_user ) {
                $users[ $_user['CreatedBy']['id'] ] = $_user['CreatedBy']['id'];
            }
            if ( !empty($users) ) {
                $conditions['ActList.created_by'] = $users;
            }
            
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array('id', 'name', 'nip'),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'fields' => array('description', 'assignment_no', 'verified')
                        )
                    )
                )
            ));
            
            // options var
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $this->set('absent_options', $absent_options);
            
            // insentive var from session
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // total insentive and performance per user
            $total_insentive = array();
            $total_perfomance = array();
            
            // total absent per user
            $total_hadir = array();
            
            // total day counted
            $total_day = array();
            
            foreach ($records as $key => $record) {
                $records[$key]['CreatedBy']['unit_code_name'] = $record['CreatedBy']['UnitCode']['name'];
                $records[$key]['CreatedBy']['position_name'] = $record['CreatedBy']['Position']['name'];
                $records[$key]['ActList']['activity'] = '';
                $records[$key]['ActList']['verificator'] = '';
                if ( isset($positions[$records[$key]['ActList']['verified_by']]) ) {
                    $records[$key]['ActList']['verificator'] = $positions[$records[$key]['ActList']['verified_by']];
                }
                if ( !empty($record['ActList']['verified']) ) {
                    $records[$key]['ActList']['verified'] = date('d/m/Y H:i:s', strtotime($record['ActList']['verified']));
                }
                
                // insentive, cut-off & performance
                $records[$key]['ActList']['insentive'] = 0;
                $records[$key]['ActList']['insentive_cutoff'] = 0;
                $records[$key]['ActList']['performance'] = 0;
                if ( $records[$key]['ActList']['absent'] == 1 || // izin
                     $records[$key]['ActList']['absent'] == 2 || // sakit
                     $records[$key]['ActList']['absent'] == 3 || // cuti
                     $records[$key]['ActList']['absent'] == 4 ) // tidak kerja
                {
                
                    $records[$key]['ActList']['insentive_cutoff'] = $insentive_cutoff;
                } else if ( $records[$key]['ActList']['absent'] == 5 || // diklat
                            $records[$key]['ActList']['absent'] == 7 ) // dinas luar
                {
                    $records[$key]['ActList']['performance'] = 100;
                }
                
                // total absent per user
                if ( !isset($total_hadir[ $record['CreatedBy']['id'] ]) ) {
                    $total_hadir[ $record['CreatedBy']['id'] ] = $absent_options;
                    foreach ( $total_hadir[ $record['CreatedBy']['id'] ] as $absent_key => $absent_val  ) {
                        $total_hadir[ $record['CreatedBy']['id'] ][ $absent_key ] = 0;
                    }
                    $total_day[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_hadir[ $record['CreatedBy']['id'] ][ $record['ActList']['absent'] ]++;
                $total_day[ $record['CreatedBy']['id'] ]++;
                
                if ( !empty($record['ActListActivity']) ) {
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            $records[$key]['ActList']['activity'] .= '<ol>';
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( !empty($desc['description']) ) {
                                    if ( $desc['verified'] ) {
                                        if ( $records[$key]['ActList']['performance'] < 100 ) {
                                            $records[$key]['ActList']['performance'] += 20;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                
                // insentive that user gets
                if ( $records[$key]['ActList']['performance'] > 0 ) {
                    $records[$key]['ActList']['insentive'] = ($records[$key]['ActList']['performance'] / 20) * $insentive_per_item;
                }
                // insentive cut-off that user gets
                if ( $records[$key]['ActList']['insentive_cutoff'] == $insentive_cutoff ) {
                    $records[$key]['ActList']['insentive'] = 0;
                    $records[$key]['ActList']['performance'] = 0;
                }
                
                // accumulate total for insentive and performance
                // per user
                if ( !isset($total_insentive[ $record['CreatedBy']['id'] ]) ) {
                    $total_insentive[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_insentive[$record['CreatedBy']['id']] += $records[$key]['ActList']['insentive'];
                if ( !isset($total_perfomance[ $record['CreatedBy']['id'] ]) ) {
                    $total_perfomance[ $record['CreatedBy']['id'] ] = 0;
                }
                $total_perfomance[$record['CreatedBy']['id']] += $records[$key]['ActList']['performance'];
            }
            
            // reformat records for this special report
            // grouped by user_id
            $record_grouped = array();
            $all_total_insentive = 0;
            $all_total_performance = 0;
            $all_total_absent = $absent_options;
            foreach ( $all_total_absent as $absent_key => $absent_val  ) {
                $all_total_absent[ $absent_key ] = 0;
            }
            foreach ( $records as $record ) {
                if ( !isset($record_grouped[ $record['CreatedBy']['id'] ]) ) {
                    $record_grouped[ $record['CreatedBy']['id'] ]['CreatedBy'] = $record['CreatedBy'];
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList'] = $record['ActList'];
                    $all_total_insentive += $total_insentive[$record['CreatedBy']['id']];
                    
                    // total absent
                    foreach ( $all_total_absent as $absent_key => $absent_val  ) {
                        $all_total_absent[ $absent_key ] += $total_hadir[$record['CreatedBy']['id']][$absent_key];
                    }
                    
                    // total performance
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['total_day'] = $total_day[$record['CreatedBy']['id']];
                    $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['performance'] =
                        $total_perfomance[$record['CreatedBy']['id']] / $total_day[$record['CreatedBy']['id']];
                        $all_total_performance += $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['performance'];
                }
                
                $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['insentive'] = $total_insentive[$record['CreatedBy']['id']];
                
                    
                $record_grouped[ $record['CreatedBy']['id'] ]['ActList']['absent'] = $total_hadir[$record['CreatedBy']['id']];
            }
            
            $this->set('records', $record_grouped);
            $this->set('all_total_absent', $all_total_absent);
            $this->set('all_total_insentive', $all_total_insentive);
            $this->set('all_total_performance', $all_total_performance > 0 ? 
                ($all_total_performance / count($record_grouped)) :
                $all_total_performance
            );
        }
        
        $this->set('show_form', $show_form);
    }

    function report_honor_per_month() {
        $show_form = true;
        $users = $this->ActList->CreatedBy->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $this->set('users', $users);
        $unit_codes = $this->ActList->CreatedBy->UnitCode->find('list', array(
            'fields' => array('id', 'name'),
            'order' => 'name ASC',
            'recursive' => -1
        ));
        $uc = 'All';
        if ( !empty($this->data['ActList']['unit_code']) && !empty($this->data['ActList']['unit_code']) ) {
            $uc = $unit_codes[$this->data['ActList']['unit_code']];
        }
        $this->set('uc', $uc);
        
        $this->set('unit_codes', $unit_codes);
        $month_name = '';
        $year_name = '';
        if ( !empty($this->data['month']['month']) && !empty($this->data['year']['year']) ) {
            $show_form = false;
            //Configure::write('debug', 0);
            $this->layout = 'printhtml';
            $month_name = $this->getMonthName( $this->data['month']['month'] ); 
            $year_name = $this->data['year']['year']; 
            
            $min_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-01';
            $max_date = $this->data['year']['year'] . '-' . $this->data['month']['month'] . '-31';
            $date = $this->getMonthName($this->data['month']['month']) . ' ' . $this->data['year']['year'];
            $this->set('date', $date);
            $conditions = array(
                'ActList.activity_date >=' => $min_date,
                'ActList.activity_date <=' => $max_date
            );
            
            $activityIdOfTeaching = $this->ActList->ActListActivity->Activity->find('list', array(
                'conditions' => array(
                    'Activity.special' => 1
                ),
                'recursive' => -1, 'fields' => array('id', 'id')
            ));
            
            // selected user from form
            $user = array();
            if ( isset($this->data['ActList']['user']) && !empty($this->data['ActList']['user']) ) {
                $conditions['ActList.created_by'] = $this->data['ActList']['user'];
                $this->ActList->CreatedBy->Behaviors->attach('Containable');
                $user = $this->ActList->CreatedBy->find('first', array(
                    'fields' => array('CreatedBy.name', 'CreatedBy.nip'),
                    'conditions' => array(
                        'CreatedBy.id' => $this->data['ActList']['user']
                    ),
                    'contain' => array(
                        'UnitCode' => array(
                            'fields' => array('name')
                        ),
                        'Position' => array(
                            'fields' => array('name')
                        )
                    )
                ));
            }
            $this->set('user', $user);
            
            // selected study_program_id form form
            $unit_code = '';
            if ( isset($this->data['ActList']['unit_code']) && !empty($this->data['ActList']['unit_code']) ) {
                $unit_code = $this->data['ActList']['unit_code'];
            }
            $this->set('unit_code', $unit_code);
            
            // begin query
            $this->ActList->Behaviors->attach('Containable');
            $records = $this->ActList->find('all', array(
                'conditions' => $conditions,
                'contain' => array(
                    'CreatedBy' => array(
                        'fields' => array(
                            'id', 'name', 'honor_attendance', 'honor_per_hour'
                        ),
                        'Position' => array(
                            'fields' => array('name', 'parent_id')
                        ),
                        'UnitCode' => array(
                            'fields' => array('name')
                        )
                    ),
                    'ActListActivity' => array(
                        'Activity' => array(
                            'fields' => array('name')
                        ),
                        'ActListActivityDescription' => array(
                            'StudentClass', 'Course',
                            'ActListActivityDescriptionStudent' => array(
                                'Student'
                            )
                        )
                    )
                )
            ));
            
            // options var
            $positions = $this->ActList->VerifiedBy->Position->find('list');
            $absent_options = $this->ActList->generateAbsentOptions();
            $this->set('absent_options', $absent_options);
            
            // insentive var from session
            $insentive_cutoff = $this->Session->read('Site.potongan_insentif_tk');
            $insentive_per_item = $this->Session->read('Site.kemampuan_insentif');
            
            // total insentive and performance
            $total_insentive = 0;
            $total_perfomance = 0;
            
            // total per absent type
            $total_hadir = $absent_options;
            foreach ( $total_hadir as $thk => $thv ) {
                $total_hadir[ $thk ] = 0;
            }
            
            // group per user_id
            $teachers = array();
            $teachers_attendances = array();
            foreach ($records as $key => $record) {
                if ( !isset($teachers[$records[$key]['CreatedBy']['id']]) ) {
                    $teachers[$records[$key]['CreatedBy']['id']] = array(
                        'name' => $record['CreatedBy']['name'],
                        'honor_attendance' => $record['CreatedBy']['honor_attendance'],
                        'honor_teaching' => $record['CreatedBy']['honor_per_hour'],
                        'total_hours' => 0, 'total_attendance' => 0,
                        'honor_per_hour' => 0, 'honor_per_attendance' => 0, 'pph21' => 0
                    );
                    $teachers_attendances[$records[$key]['CreatedBy']['id']] = array();
                }
                
                // attendance unique per date
                $teachers_attendances[$records[$key]['CreatedBy']['id']][$record['ActList']['activity_date']] = 1;
                
                if ( !empty($record['ActListActivity']) ) {
                    foreach ( $record['ActListActivity'] as $key2 => $activity ) {
                        
                        if ( !empty($activity['ActListActivityDescription']) ) {
                            foreach ( $activity['ActListActivityDescription'] as $key3 => $desc ) {
                                if ( in_array($activity['activity_id'], $activityIdOfTeaching) &&
                                     !empty($desc['Course']) && ($desc['end_class'] > $desc['start_class']) )
                                {
                                    $time_qty = $this->__getTimeQty($desc['start_class'], $desc['end_class']);
                                    if ( $unit_code ) {
                                        if ( isset($desc['StudentClass']['study_program_id']) &&
                                             $desc['StudentClass']['study_program_id'] == $unit_code )
                                        {
                                            $teachers[$records[$key]['CreatedBy']['id']]['total_hours'] += 
                                                ($time_qty ? $time_qty : 0);
                                        }
                                    } else {
                                        $teachers[$records[$key]['CreatedBy']['id']]['total_hours'] += 
                                                ($time_qty ? $time_qty : 0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
            
            $totals = array(
                'honor' => 0, 'pph21' => 0, 'received' => 0
            );
            foreach ($teachers as $k => $teacher) {
                if ( !$teacher['total_hours'] ) {
                    unset($teachers[$k]);
                    continue;
                } else {
                    if ( $teachers[$k]['honor_teaching'] ) {
                        $teachers[$k]['honor_per_hour'] = 50000 * $teacher['total_hours'];
                    }
                    
                    $teachers[$k]['honor_per_attendance'] = 0;
                    if ( $teachers[$k]['honor_attendance'] ) {
                        $teachers[$k]['total_attendance'] = count($teachers_attendances[$k]);
                        $teachers[$k]['honor_per_attendance'] = 50000 * $teachers[$k]['total_attendance'];
                    }
                    
                    $teachers[$k]['pph21'] = 0;
                    $teachers[$k]['honor_per_hour_minus_tax'] = $teachers[$k]['honor_per_hour'];
                    if ( $teachers[$k]['honor_per_hour'] > 1203000 ) {
                        $teachers[$k]['pph21'] = ($teachers[$k]['honor_per_hour'] * 5) / 100;
                        $teachers[$k]['honor_per_hour_minus_tax'] = 
                            $teachers[$k]['honor_per_hour'] - $teachers[$k]['pph21'];
                    }
                    $teachers[$k]['total_honor'] = $teachers[$k]['honor_per_hour_minus_tax'];
                    $teachers[$k]['total_received'] = $teachers[$k]['total_honor'] +
                                                      $teachers[$k]['honor_per_attendance'];
                    
                    $totals['honor'] += $teachers[$k]['total_honor'];
                    $totals['pph21'] += $teachers[$k]['pph21'];
                    $totals['received'] += $teachers[$k]['total_received'];
                }
            }
            
            $this->set('records', $teachers);
            $this->set('totals', $totals);
            $this->set('month_name', $month_name);
            $this->set('year_name', $year_name);
        }
        
        $this->set('show_form', $show_form);
    }
    
    public function orphan() {
        $this->autoRender = false;
        
        $this->ActList->ActListActivity->Behaviors->attach('Containable');
        $activities = $this->ActList->ActListActivity->find('all', array(
            'contain' => array('ActList')
        ));
        $counter = 0;
        foreach ($activities as $k => $a) {
            if ( isset($a['ActList']['id']) && $a['ActList']['id'] ) {
                unset($activities[$k]);
            } else {
                $counter++;
            }
        }
        echo "Found $counter missing ActList rel on ActListActivity. <br />";
        
        $this->ActList->ActListActivity->ActListActivityDescription->Behaviors->attach('Containable');
        $desc = $this->ActList->ActListActivity->ActListActivityDescription->find('all', array(
            'contain' => array('ActListActivity')
        ));
        $counter = 0;
        foreach ($desc as $k => $d) {
            if ( isset($d['ActListActivity']['id']) && $d['ActListActivity']['id'] ) {
                unset($desc[$k]);
            } else {
                $counter++;
            }
        }
        echo "Found $counter missing ActListActivity rel on ActListActivityDescription. <br />";
        
        $this->ActList->ActListActivity->ActListActivityDescription
             ->ActListActivityDescriptionStudent->Behaviors->attach('Containable');
        $students = $this->ActList->ActListActivity->ActListActivityDescription
                     ->ActListActivityDescriptionStudent->find('all', array(
            'contain' => array('ActListActivityDescription')
        ));
        $counter = 0;
        foreach ($students as $k => $s) {
            if ( isset($s['ActListActivityDescription']['id']) && $s['ActListActivityDescription']['id'] ) {
                unset($students[$k]);
            } else {
                $counter++;
            }
        }
        echo "Found $counter missing ActListActivityDescription rel on ActListActivityDescriptionStudent. <br />";
        
        die;
    }
    
    public function get_courses($class_id) {
        Configure::write('debug', 0);
        $this->layout = 'ajax';
        
        $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->Behaviors->attach('Containable');
        $class = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->find('first', array(
            'conditions' => array(
                'StudentClass.id' => $class_id
            ),
            'contain' => 'StudyProgram'
        ));
        pr($class);
        $program = $class['StudyProgram']['id'];
        
        $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->StudyProgram->bindModel(array(
            'belongsTo' => array(
                'Course'
            )
        ));
        $courses = $this->ActList->ActListActivity->ActListActivityDescription->StudentClass->StudyProgram->Course->find(
            'list', array(
                'conditions' => array(
                    'Course.study_program_id' => $program
                ),
                'order' => 'Course.name ASC'
            )
        );        
        $this->set('courses', $courses);
    }

    public function get_profile($user_id) {
        Configure::write('debug', 0);
        $this->layout = 'json/default';

        $profile = array();
        $user = $this->ActList->CreatedBy->find('first', array(
            'conditions' => array(
                'id' => $user_id,
            ),
            'recursive' => -1
        ));
        if ( $user ) {
            $profile = $user['CreatedBy'];
        }

        $this->set('profile', $profile);
    }

    public function get_activities($position_id) {
    
    }

    private function __getTimeQty($start, $end) {
        $qty = '';
        if (!empty($start) && !empty($end) && $end >= $start) {
            $qty = $end-$start;
            
            // cek jam istirahat pertama
            if ( $start <= $this->break_hours[0] && $end >= $this->break_hours[1] ) {
                $qty -= 1;
            }
            
            // cek jam istirahat kedua
            if ( $start <= $this->break_hours[2] && $end >= $this->break_hours[3] ) {
                $qty -= 2;
            }

            if ( $start == 5 && $end == 9 ) {
                // cek jam 10.15 - 13.30 agar dihitung 3 jam
                $qty = 3;
            } else if ( $start == 6 && $end == 9 ) {
                // cek jam 11 - 13.30 agar dihitung 2 jam
                $qty = 2;
            } else if ( $start == 9 && $end == 12 ) {
                $qty = 2;
            }
        }
        return $qty;
    }
}
?>
